chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log("background receive message " + request);
  if(request.action == 'openNewTab') {
    chrome.tabs.create({ url: request.url });
    sendResponse('succc')
  } else if(request.action == "getStorageData") {
    chrome.storage.session.get(["uname", "uid"], function(data) {
      sendResponse(data);
    });
  } else if(request.action == "saveUserInfo") {
    chrome.storage.session.set({ uname: request.uname, uid: request.uid }, function(result) {
      sendResponse('succ')
    });
  }
  return true;
});

// 监听标签页更新事件
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  // 检查页面是否完全加载完成
  const url = tab.url;
  const controlURL = [ 
      "sooxie.com/detail",
      "haohuo.jinritemai.com",
      "item.taobao.com/item.htm",
      "detail.tmall.com/item.htm",
      "detail.vip.com",
      "item.jd.com",
      "data.zhiyitech.cn","detail.1688.com","xiaohongshu.com"];
  var exist = controlURL.find(item => url.indexOf(item) > -1);
  if (changeInfo.status === 'complete' && exist) {
    // 页面加载完成后的逻辑
    console.log('Page loaded successfully!');
    // 这里可以执行您想要在页面加载完成后进行的操作
    // chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {   //向内容也发送消息，在页面中添加操作按钮
    //注入脚本
    // const scriptUrl = chrome.runtime.getURL('scripts/script.js');
    // const scriptCode = `
    //   console.log('Hello from executed script!');
    //   document.body.style.backgroundColor = 'lightblue';
    // `;
    // chrome.scripting.executeScript({
    //   target: {tabId: tabId},
    //   function(script) {
    //     window.extension = {
    //       sayHello() {
    //         console.log("HelloWorld");
    //       }
    //     }
    //   },
    //   args: [scriptCode]
    // }).then(() => {
    //   console.log("script injected")
    // });
    chrome.tabs.sendMessage(tabId, {"action": "button"}, function(response) {
        console.log("MSG " + response.response);
    })
  }
});

// 创建右键菜单项
chrome.contextMenus.create({
  id: "EccDN1234",
  title: "采集商品信息",
  contexts: ["page"],
  targetUrlPatterns: ["*://item.taobao.com/item.htm*", 
    "*://*.sooxie.com/detail/*", 
    "*://haohuo.jinritemai.com/*",
    "*://detail.tmall.com/item.htm*", 
    "*://detail.vip.com/*",
    "*://item.jd.com/*", 
    "*://data.zhiyitech.cn/itemDetail/*",
    "*://www.xiaohongshu.com/goods-detail/*",
    "*://detail.1688.com/*"] // 通过 targetUrlPatterns 属性指定特定网站的链接
});
  
// 添加点击事件处理程序
chrome.contextMenus.onClicked.addListener(function(info, tab) {
  if (info.menuItemId === "EccDN1234") {
    chrome.storage.session.get(["uname", "uid"], function(result) {
      if(result && result.uid && result.uname) {
          // 这里执行您的点击事件处理逻辑
          let tabId = tab.id;
          //获取链接地址
          const url  = tab.url;
          /**
           * 识别平台
           */
          var platform = (url.indexOf("detail.tmall.com") > -1 || url.indexOf("item.taobao.com") > -1) ? "淘宝" : 
            (url.indexOf("detail.vip.com") > -1 ? "唯品会" : 
                (url.indexOf("item.jd.com") > -1 ? "京东" : 
                    (url.indexOf("detail.1688.com") > -1 ? "1688" : (
                        url.indexOf("haohuo.jinritemai.com") > -1 ? "抖音" : (
                            url.indexOf("sooxie.com") > -1 ? "搜鞋" : (
                              url.indexOf("xiaohongshu.com") > -1 ? "小红书" : ""
                            )
                        )))
                )
            );
          if(platform != '' && platform != null) {
            chrome.tabs.sendMessage(tabId, {"platform": platform,"action": "getInfo"}, function(response) {
              if(response.response) {
                  const params = response.response;
                  params.url = url;
                  params.platform = platform;
                  params.uname = result.uname;
                  params.uid = result.uid;
                  const encodedParams = encodeURIComponent(JSON.stringify(params));
                  chrome.tabs.create({ url: chrome.runtime.getURL("newpage.html?data=" + encodedParams) });
              }
            })
          } else {
            var otherPlatform = url.indexOf("data.zhiyitech.cn") > -1 ? "知衣" : "";
            if(otherPlatform == '知衣') {
              // var msg = "即将打开商品页面进行采集，是否打开";
              // chrome.tabs.sendMessage(tabId, {"platform": otherPlatform,"action": "open_zy_confirm","msg": msg}, function(response) {
              //   console.log(response);
              // })
            }
          }
      } else {
          chrome.tabs.sendMessage(tab.id, { action: "open_confirm", msg: "未识别到找样人，是否登录中台系统？"});
      }
    });
  }
});

function openConfirm(msg) {
  return confirm(msg)
}